package com.honeycomb.common.interceptor;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.honeycomb.common.SessionTimeoutException;
import com.honeycomb.utils.SystemConstants;

@Component
public class SystemInterceptor extends HandlerInterceptorAdapter {
	
	protected Logger logger = LogManager.getLogger(this.getClass());
	private List<String> allowUrls;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		
		String requestUrl = request.getRequestURI();
		
		if (requestUrl.startsWith(request.getContextPath() + "/resource/") ) {
			return true;
		}
        
        for(String url : allowUrls) {
        	
            if(requestUrl.endsWith(url)) {
            	if (logger.isDebugEnabled()) {
            		logger.debug("This url is marked as allowed:" + requestUrl);
            	}
                return true;  
            }  
        }  
 
        if(request.getSession().getAttribute(SystemConstants.LOGINUSER_SESSION_NAME) != null) {  
            return true;  
        } else {
        	logger.info("Session timout when access " + requestUrl);
            throw new SessionTimeoutException();  
        }  
		
	}

	public List<String> getAllowUrls() {
		return allowUrls;
	}

	public void setAllowUrls(List<String> allowUrls) {
		this.allowUrls = allowUrls;
	}
	
}
